package com.army.filemanage.web;

import com.army.filemanage.databean.FileCriteria;
import com.army.filemanage.databean.StandardResponse;
import com.army.filemanage.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Iterator;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Autowired
    FileService fileService;

    @PostMapping("/upload")
    public StandardResponse upload(String fileId, MultipartHttpServletRequest multiPartRequest) {
        log.info("**Upload File Controller!");

        FileCriteria criteria = new FileCriteria();
        criteria.setFileId(fileId);

        try {
            //upload file
            Iterator<String> itr =  multiPartRequest.getFileNames();
            MultipartFile mpf = null;

            while(itr.hasNext()){
                mpf = multiPartRequest.getFile(itr.next());
                break;
            }

            byte[] fileByteArr = null;
            if (null != mpf && !mpf.isEmpty()) {
                String originalFileName = mpf.getOriginalFilename();
                log.info(originalFileName);
                criteria.setFileName("");
                String fileExtension = FilenameUtils.getExtension(originalFileName);
                criteria.setFileExtension(fileExtension);
                fileByteArr = mpf.getBytes();
                criteria.setFileByteArray(fileByteArr);

                criteria.setFileName(originalFileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }


        return fileService.uploadFile(criteria);
    }

}
